package com.pi.base.util;

import com.pi.base.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

public class FileTool {
    private static final Logger logger = LoggerFactory.getLogger(FileTool.class);

    public static boolean fileUpload(MultipartFile file,String fileDirPath,String fileName) {
        if (file.isEmpty()) {
            return false;
        }
        fileName = StringUtils.isEmpty(fileName) ? file.getOriginalFilename() :fileName;
        String filePath = new StringBuffer(fileDirPath).append(fileName).toString();
        if(!mkdir(fileDirPath)){
            throw new ServiceException("广告文件夹创建失败");
        }
        try {
            file.transferTo(new File(filePath)); // 保存文件
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean mkdir(String dirPath){
        File dir = new File(dirPath);
        if(!dir.exists()){
            return dir.mkdir();
        }
        return true;
    }
}
